<template>
  <div class="avatar-upload-component">
    <el-dialog title="头像维护" :visible.sync="dialogVisible" width="350px" center>
      <div class="user-info-section">
        <div class="info-item">
          <span class="info-label">姓名：</span>
          <span class="info-value">{{ userInfo.name }}</span>
        </div>
        <div class="info-item">
          <span class="info-label">学号：</span>
          <span class="info-value">{{ userInfo.no }}</span>
        </div>
      </div>

      <div class="upload-section">
        <el-upload
          class="avatar-uploader"
          action=""
          :show-file-list="false"
          :before-upload="beforeAvatarUpload"
          :http-request="customUpload"
        >
          <img v-if="imageUrl" :src="imageUrl" class="avatar" />
          <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          <!-- 上传中遮罩 -->
          <div v-if="uploadLoading" class="upload-loading-mask">
            <el-loading-spinner></el-loading-spinner>
            <span>上传中...</span>
          </div>
        </el-upload>
      </div>

      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { sysuseravatar } from '@/api/comment/studentList.js';
export default {
  data() {
    return {
      dialogVisible: false,
      imageUrl: '',
      userInfo: {},
      uploadLoading: false
    };
  },
  computed: {},
  watch: {},
  created() {},
  mounted() {},
  methods: {
    open(val) {
      this.dialogVisible = true;
      this.userInfo = val; // 保存用户信息

      if (val.avatar) {
        this.imageUrl = `https://accommodation-booking-api.sicnu.edu.cn/loft/getImg/avatar/${val.avatar}`;
      } else {
        this.imageUrl = '';
      }
    },

    // 上传前校验
    beforeAvatarUpload(file) {
      const isJPG = file.type === 'image/jpeg' || file.type === 'image/png';
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isJPG) {
        this.$message.error('只能上传 JPG/PNG 格式的图片!');
      }
      if (!isLt2M) {
        this.$message.error('上传图片大小不能超过 2MB!');
      }
      return isJPG && isLt2M;
    },

    // 自定义上传处理
    async customUpload(file) {
      console.log(file);

      // 将图片转换为base64
      const base64Data = await this.convertFileToBase64(file.file);

      try {
        // 显示上传中状态
        this.uploadLoading = true;

        const res = await sysuseravatar({
          no: this.userInfo.no,
          img: base64Data
        });
        if (res.code == 0) {
          // 上传成功
          this.$message.success('上传成功');
          this.dialogVisible = false;
          // 触发父组件的search事件
          this.$emit('search', {});
        } else {
          // 上传失败
          this.$message.warning(res.msg);
        }
      } catch (error) {
        this.$message.error('头像上传失败，请重试');
      } finally {
        // 关闭上传中状态
        this.uploadLoading = false;
      }
    },

    // 将文件转换为base64
    convertFileToBase64(file) {
      return new Promise((resolve, reject) => {
        const reader = new FileReader();
        reader.onload = (e) => {
          // 获取base64数据并去掉前缀
          const base64 = e.target.result.split(',')[1];
          resolve(base64);
        };
        reader.onerror = (error) => {
          reject(error);
        };
        reader.readAsDataURL(file);
      });
    }
  },

  components: {}
};
</script>

<style lang="scss" scoped>
// 用户信息区域样式
.user-info-section {
  margin-bottom: 20px;
  padding: 15px;
  background-color: #f5f7fa;
  border-radius: 8px;
  border: 1px solid #ebeef5;

  .info-item {
    display: flex;
    align-items: center;
    margin-bottom: 8px;

    &:last-child {
      margin-bottom: 0;
    }

    .info-label {
      font-weight: 500;
      color: #606266;
      width: 60px;
      flex-shrink: 0;
    }

    .info-value {
      color: #303133;
      font-size: 14px;
      flex: 1;
    }
  }
}

// 上传区域样式
.upload-section {
  display: flex;
  justify-content: center;
  margin-bottom: 10px;
}

// 头像上传器样式
.avatar-uploader {
  .el-upload {
    border: 2px dashed #d9d9d9;
    border-radius: 10px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    transition: all 0.3s ease;
    background-color: #fafafa;

    &:hover {
      border-color: #409eff;
      background-color: #ecf5ff;
    }
  }

  .avatar-uploader-icon {
    font-size: 36px;
    color: #c0c4cc;
    width: 200px;
    height: 200px;
    line-height: 200px;
    text-align: center;
  }

  .avatar {
    width: 200px;
    height: 200px;
    display: block;
    border-radius: 8px;
    object-fit: cover;
  }
}

// 上传中遮罩样式
.upload-loading-mask {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(255, 255, 255, 0.9);
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  z-index: 10;
  border-radius: 8px;
  backdrop-filter: blur(2px);

  .el-loading-spinner {
    margin-bottom: 15px;
    animation-duration: 1.2s;
  }

  span {
    color: #409eff;
    font-size: 16px;
    font-weight: 500;
  }
}

// 对话框底部样式
.dialog-footer {
  display: flex;
  justify-content: center;
  padding: 15px 0 5px;

  .el-button {
    min-width: 80px;
    padding: 9px 20px;
  }

  .el-button + .el-button {
    margin-left: 20px;
  }
}

// 响应式调整
@media (max-width: 400px) {
  .avatar-uploader {
    .avatar-uploader-icon,
    .avatar {
      width: 160px;
      height: 160px;
      line-height: 160px;
    }
  }
}
</style>
